package com.cennavi.minemapdemo.activity.exlayer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.util.Config;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.geometry.LatLngBounds;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.AnimatedMarkerLayer;
import com.minedata.minemap.overlay.AnimatedMarkerOptions;
import com.minemap.geojson.Point;
import com.minemap.turf.TurfMeasurement;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AnimatedMarkerActivity extends AppCompatActivity {
    private MapView mapView;
    private static MineMap mineMap;
    private AnimatedMarkerLayer animatedMarkerLayer;
    private List<AnimatedMarkerOptions.AnimatedMarkerItem> randomCars = new ArrayList<>();
    private String bitmapName = "car";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);

        setContentView(R.layout.activity_main_layer);
        mapView = findViewById(R.id.mapView);
        mapView.setApiBaseUrl(Config.API_BASE_URL);
        mapView.setApiUrl(Config.API_URL);
        mapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(final MineMap mineMap) {
                AnimatedMarkerActivity.mineMap = mineMap;
                mineMap.setStyleUrl(Config.BASE_URL + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {

                    @Override
                    public void onStyleLoaded(String style) {
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_car_top);
                        mineMap.addImage(bitmapName, bitmap);
                        AnimatedMarkerOptions options = new AnimatedMarkerOptions("animatedmarkerlayer");
                        animatedMarkerLayer = mineMap.addLayer(options);
                        addRandomCars();
                        animatedMarkerLayer.setOnAnimationEndListener(new AnimatedMarkerLayer.OnAnimationEndListener() {
                            @Override
                            public void onAnimationEnd() {
                                updateRandomCars();
                            }
                        });
                    }
                });

                //设置是否开启动态刷新，默认是不开启
                mineMap.setRepaint(false);
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.setCameraPosition(
                        //41.805629,123.432359   沈阳
                        //34.2419937,108.9418989 西安   108.81292 34.36734
                        //39.897424, 116.356508  北京    116.3564, 39.8974
                        //18.162968，102.591348  老挝万象附近
                        new CameraPosition.Builder()
                                .target(new LatLng(41.805629, 123.432359))//设置相机指向的位置
                                .zoom(13)//设置相机缩放等级
                                .tilt(0)//设置相机的俯视角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                //设置是否显示地图调试信息，默认是不显示
                mineMap.setDebugActive(false);
            }
        });
    }

    @Override
    protected void onStart() {
        if (mapView != null) {
            mapView.onStart();
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        if (mapView != null)
            mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mapView != null)
            mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mapView != null)
            mapView.onStop();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (animatedMarkerLayer != null) {
            animatedMarkerLayer.cancelAnimators();
        }

        if (mapView != null)
            mapView.onDestroy();

        super.onDestroy();
    }

    private void addRandomCars() {
        for (int i = 0; i < 10; i++) {
            LatLng start = getLatLngInBounds();
            LatLng end = getLatLngInBounds();
            AnimatedMarkerOptions.AnimatedMarkerItem randomCar = new AnimatedMarkerOptions.AnimatedMarkerItem(start, end)
                    .icon(bitmapName).iconRotate(getBearing(start, end)).setDuration((long) (4 * start.distanceTo(end)));
            randomCars.add(randomCar);
        }

        animatedMarkerLayer.setAll(randomCars);
        animatedMarkerLayer.update();
        animatedMarkerLayer.startAnimators();
    }

    private void updateRandomCars() {
        for (AnimatedMarkerOptions.AnimatedMarkerItem randomCar : randomCars) {
            LatLng start = randomCar.getTrackEndPoint();
            LatLng end = getLatLngInBounds();
            randomCar.trackStartPoint(start).trackEndPoint(end)
                    .iconRotate(getBearing(start, end)).setDuration((long) (4 * start.distanceTo(end)));
        }

        animatedMarkerLayer.setAll(randomCars);
        animatedMarkerLayer.update();
        animatedMarkerLayer.startAnimators();
    }

    private static float getBearing(LatLng from, LatLng to) {
        return (float) TurfMeasurement.bearing(
                Point.fromLngLat(from.getLongitude(), from.getLatitude()),
                Point.fromLngLat(to.getLongitude(), to.getLatitude())
        );
    }

    private LatLng getLatLngInBounds() {
        LatLngBounds bounds = mineMap.getProjection().getVisibleRegion().getLatLngBounds();
        Random generator = new Random();
        double randomLat = bounds.getLatSouth() + generator.nextDouble()
                * (bounds.getLatNorth() - bounds.getLatSouth());
        double randomLon = bounds.getLonWest() + generator.nextDouble()
                * (bounds.getLonEast() - bounds.getLonWest());
        return new LatLng(randomLat, randomLon);
    }
}
